import axios from 'axios';
import FormData from 'form-data';
import { File } from 'buffer';
import fs from 'fs';



const PINATA_API_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySW5mb3JtYXRpb24iOnsiaWQiOiJlMzc2MDFlNy1kNDA5LTRiNTYtOGU4MS1kMDNlZTE0NzQ5YWMiLCJlbWFpbCI6InRtZG9nNjY2NkBnbWFpbC5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwicGluX3BvbGljeSI6eyJyZWdpb25zIjpbeyJkZXNpcmVkUmVwbGljYXRpb25Db3VudCI6MSwiaWQiOiJGUkExIn0seyJkZXNpcmVkUmVwbGljYXRpb25Db3VudCI6MSwiaWQiOiJOWUMxIn1dLCJ2ZXJzaW9uIjoxfSwibWZhX2VuYWJsZWQiOmZhbHNlLCJzdGF0dXMiOiJBQ1RJVkUifSwiYXV0aGVudGljYXRpb25UeXBlIjoic2NvcGVkS2V5Iiwic2NvcGVkS2V5S2V5IjoiYzkxOTdlY2I1NDYwZDVlMjNkNmYiLCJzY29wZWRLZXlTZWNyZXQiOiJlNzg0YjU1MGEzMDA4NjM5ODcwYTE3MjU3NGE2ZGQ0NjE0ZTkxMGYwYTFkNzIwYzQyYzNmZTI3MzNiMzIzYmVhIiwiZXhwIjoxNzc5MTkxMjc3fQ.m2XjbconRNd_qnzIu8buOpZN0DoYfo2gTSck5Z6eAzk';
const PINATA_API_SECRET = 'YOUR_PINATA_API_SECRET'; // 从 Pinata 获取 API 密钥

// 上传单个文件到 Pinata 并返回 IPFS Hash
export const uploadFileToPinata = async (file,fileName) => {
  const formData = new FormData();
  formData.append('file',file,{filename:fileName});
    
  try {
    const response = await axios.post('https://api.pinata.cloud/pinning/pinFileToIPFS', formData, {
      headers: {
        Authorization : `Bearer ${PINATA_API_KEY}`,
        ...formData.getHeaders()

      },
    });
    console.log('Pinata upload response:', response.data);
    if (response.data && response.data.IpfsHash) {
      return response.data.IpfsHash;
    } else {
      throw new Error('Pinata upload failed');
    }
  } catch (error) {
    console.error('Error uploading file to Pinata:', error);
    throw error;
  }
};

// 上传多个文件到 Pinata 并返回 IPFS Hash 数组
export const uploadMultipleFilesToPinata = async (files) => {
  const ipfsHashes = [];

  try {
    for (let i = 0; i < files.length; i++) {
      const ipfsHash = await uploadFileToPinata(files[i]);
      ipfsHashes.push(ipfsHash);
    }

    return ipfsHashes;
  } catch (error) {
    console.error('Error uploading multiple files:', error);
    throw error;
  }
};

// 获取文件的 IPFS URL
export const getFileIpfsUrl = (ipfsHash) => {
  return `https://ipfs.io/ipfs/${ipfsHash}`;
};

// 上传图片文件并返回 IPFS URL
export const uploadFileAndGetUrl = async (file) => {
  const ipfsHash = await uploadFileToPinata(file);
  const ipfsUrl = getFileIpfsUrl(ipfsHash);
  return ipfsUrl;
};

// 上传多个文件并返回 IPFS URL 数组
export const uploadMultipleFilesAndGetUrls = async (files) => {
  const ipfsHashes = await uploadMultipleFilesToPinata(files);
  const ipfsUrls = ipfsHashes.map((hash) => getFileIpfsUrl(hash));
  return ipfsUrls;
};
